package org.example;

import java.lang.instrument.*;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.ProtectionDomain;

import javassist.*;

import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;


public class AgentDemo {

    static {
        try {
            // 获取当前类加载器加载的 JAR 文件 URL
            URL jarUrl = AgentDemo.class.getProtectionDomain().getCodeSource().getLocation();
            Path jarPath = Paths.get(jarUrl.toURI()).getParent();
            System.setProperty("log.dir", jarPath.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("premain start");
        ClassPool cp = ClassPool.getDefault();
        try {
            cp.insertClassPath(new LoaderClassPath(Thread.currentThread().getContextClassLoader()));
            //查看返回信息，url code message
            CtClass cc = cp.get("okhttp3.RealCall");
//            System.out.println(cc.toString());

            CtMethod b = cc.getDeclaredMethod("execute");
//            System.out.println(b);

            b.insertBefore("org.slf4j.LoggerFactory.getLogger(\"org.example.agent.httplogger\").info(\"---------------查看返回信息，url code message\");");
            b.insertAfter("org.slf4j.LoggerFactory.getLogger(\"org.example.agent.httplogger\").info(\"Response: {}\", $_);");
            cc.toClass();


            //获取第三方返回信息，response.body
            CtClass cc1 = cp.get("okhttp3.ResponseBody");
//            System.out.println(cc1.toString());

            CtMethod b1 = cc1.getDeclaredMethod("string");
//            System.out.println(b1);

            b1.insertBefore("org.slf4j.LoggerFactory.getLogger(\"org.example.agent.httplogger\").info(\"---------------获取第三方返回信息-->response.body\");");
            b1.insertAfter("org.slf4j.LoggerFactory.getLogger(\"org.example.agent.httplogger\").info(\"Body: {}\", $_);");
            cc1.toClass();


            //若有执行RequestBody的构建工作，则 打印出请求的格式（json），请求体信息
            CtClass cc2 = cp.get("okhttp3.RequestBody");
//            System.out.println(cc2.toString());

            CtMethod b2 = cc2.getDeclaredMethod("create");
//            System.out.println(b2);

            b2.insertBefore("org.slf4j.LoggerFactory.getLogger(\"org.example.agent.httplogger\").info(\"---------------若有执行RequestBody的构建工作，则打印出请求的格式（json），请求体信息\");");
            b2.insertAfter("org.slf4j.LoggerFactory.getLogger(\"org.example.agent.httplogger\").info(\"MediaType: {}\", $1);");
            b2.insertAfter("org.slf4j.LoggerFactory.getLogger(\"org.example.agent.httplogger\").info(\"Content: {}\", $2);");
            cc2.toClass();



        } catch (Exception e) {
            System.out.println("cc出现异常");
            e.printStackTrace();
        }
    }
}

